//
//  NSObject+WDExtension.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2017/3/8.
//  Copyright © 2017年 王笛. All rights reserved.
//

#import "NSObject+WDExtension.h"
#define WDSPACE 5.0f

@implementation NSObject (WDExtension)

- (CGSize)sizeWithString:(NSString *)string font:(UIFont *)font constraintSize:(CGSize)constraintSize
{
    CGSize stringSize = CGSizeZero;
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    [style setLineSpacing:WDSPACE];
    
    if ([string rangeOfString:@"\n"].location != NSNotFound) {//又换行
        
        NSArray *strArr = [string componentsSeparatedByString:@"\n"];
        
        CGFloat titleH = 0;
        
        for (int i = 0; i < strArr.count; i++) {
            
            NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:style};
            NSInteger options = NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin;
            CGRect stringRect = [strArr[i] boundingRectWithSize:constraintSize options:options attributes:attributes context:NULL];
            
            titleH += stringRect.size.height;
            
            stringSize = CGSizeMake(stringRect.size.width, titleH);
            
        }
        
    } else {//没有换行
        
        NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:style};
        NSInteger options = NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin;
        CGRect stringRect = [string boundingRectWithSize:constraintSize options:options attributes:attributes context:NULL];
        stringSize = stringRect.size;
    }
    
    return stringSize;
}

@end
